package com.approval.security;

import com.approval.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 权限验证拦截器
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    
    @Autowired
    private AuthService authService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        
        // 检查方法上的权限注解
        RequirePermission methodAnnotation = method.getAnnotation(RequirePermission.class);
        if (methodAnnotation != null) {
            if (!checkPermission(methodAnnotation)) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":403,\"message\":\"权限不足\"}");
                return false;
            }
        }
        
        // 检查类上的权限注解
        RequirePermission classAnnotation = method.getDeclaringClass().getAnnotation(RequirePermission.class);
        if (classAnnotation != null) {
            if (!checkPermission(classAnnotation)) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":403,\"message\":\"权限不足\"}");
                return false;
            }
        }
        
        return true;
    }
    
    private boolean checkPermission(RequirePermission annotation) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        // 获取当前用户ID（这里需要根据你的认证方式调整）
        Long userId = getCurrentUserId(authentication);
        if (userId == null) {
            return false;
        }
        
        // 检查权限编码
        if (!annotation.value().isEmpty()) {
            return authService.hasPermission(userId, annotation.value());
        }
        
        // 检查资源和操作
        if (!annotation.resource().isEmpty() && !annotation.action().isEmpty()) {
            return authService.hasPermission(userId, annotation.resource(), annotation.action());
        }
        
        return true;
    }
    
    private Long getCurrentUserId(Authentication authentication) {
        // 从UserPrincipal中获取用户ID
        if (authentication.getPrincipal() instanceof UserPrincipal) {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            return userPrincipal.getId();
        }
        return null;
    }
}
